package cn.swust.score.controller;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.github.pagehelper.PageInfo;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.swust.score.basepojo.ResultResponse;
import cn.swust.score.pojo.Candidate;
import cn.swust.score.pojo.QueryCandidate;
import cn.swust.score.service.CandidateService;
import cn.swust.score.util.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(tags = "候选人信息")
@RestController
@Validated
@RequestMapping("/candidate")
public class CandidateController {

	@Value("${files.path}")
	private String filesPath;
	@Autowired
	public CandidateService candidateService;

	@ApiOperation(value = "删除记录")
	@DeleteMapping(value = "/del")
	public ResultResponse<Integer> delById(@ApiParam(required = true, value = "查询记录编号") @RequestBody Integer id) {
		return new ResultResponse<Integer>(candidateService.delById(id));
	}

	@ApiOperation(value = "新增记录")
	@PostMapping(value = "/add")
	@ApiParam(required = true, value = "记录值")
	public ResultResponse<Candidate> save(@Valid @RequestBody Candidate record) {
		if (candidateService.save(record) <= 0)
			record = null;
		else {
			record = candidateService.getById(record.getId());
			candidateService.sort(record.getScoreInfoId());
		}
		return new ResultResponse<Candidate>(record);
	}

	@ApiOperation(value = "根据ID查询记录")
	@PutMapping(value = "/get")
	public ResultResponse<Candidate> getById(
			@ApiParam(required = true, value = "查询记录编号") @RequestBody @Valid Integer id) {

		Candidate candidate = candidateService.getById(id);
		return new ResultResponse<Candidate>(candidate);
	}

	@ApiParam(required = true, value = "记录内容")
	@PutMapping(value = "/edit")
	public ResultResponse<Candidate> editById(@Valid @RequestBody Candidate record) {
		if (candidateService.editById(record) <= 0)
			record = null;
		else {
			record = candidateService.getById(record.getId());
			candidateService.sort(record.getScoreInfoId());
		}
		return new ResultResponse<Candidate>(record);
	}

	@ApiOperation(value = "详细列表查询")
	@PostMapping("/list")
	public ResultResponse<PageInfo<Candidate>> list(
			@ApiParam(required = false, value = "查询参数") @Valid @RequestBody QueryCandidate param) {
		return new ResultResponse<PageInfo<Candidate>>(
				candidateService.list(param.getPageNum(), param.getPageSize(), param));
	}

	@ApiOperation(value = "导出excel")
	@PostMapping("/excel")
	public void excel(@ApiParam(required = false, value = "查询参数") @Valid @RequestBody QueryCandidate param,
			HttpServletResponse response) throws IOException {
		PageInfo<Candidate> listData = candidateService.list(0, 0, param);

		Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), Candidate.class, listData.getList());

		// 告诉浏览器用什么软件可以打开此文件
		response.setHeader("content-Type", "application/vnd.ms-excel");
		// 下载文件的默认名称
		response.setHeader("Content-Disposition", "attachment;filename=候选人.xls");
		workbook.write(response.getOutputStream());
	}

	@ApiOperation(value = "导入excel")
	@PostMapping("/import")
	public ResultResponse<String> importExcel(@ApiParam(required = false, value = "导入文件") @Valid MultipartFile file)
			throws IOException, Exception {
		String fileOrigName = file.getOriginalFilename();
		if (!fileOrigName.contains(".")) {
			throw new IllegalArgumentException("Lack of suffix name.");
		}
		String md5 = FileUtil.fileMd5(file.getInputStream());
		fileOrigName = fileOrigName.substring(fileOrigName.lastIndexOf("."));
		String prefix = fileOrigName.substring(fileOrigName.lastIndexOf(".") + 1);
		String pathname = FileUtil.getPath() + md5 + fileOrigName;
		String fullPath = filesPath + pathname;
		FileUtil.saveFile(file, fullPath);
		ImportParams params = new ImportParams();
		// params.setTitleRows(1);
		params.setHeadRows(1);

		List<Candidate> personList = ExcelImportUtil.importExcel(file.getInputStream(), Candidate.class, params);

		candidateService.save(personList);
		candidateService.sort(personList.get(0).getScoreInfoId());
		return new ResultResponse<String>(0, "OK", file.getOriginalFilename());
	}

	@ApiOperation(value = "导入单张照片(可以多张)")
	@PostMapping("/img")
	public ResultResponse<Integer> importImage(
			@ApiParam(required = false, value = "导入照片压缩包") @Valid MultipartFile[] files) throws IOException, Exception {
		for (int i = 0; i < files.length; i++) {
			MultipartFile file = files[i];
			String fileOrigName = file.getOriginalFilename();
			if (!fileOrigName.contains("."))
				throw new IllegalArgumentException("缺少后缀名.");

			fileOrigName = fileOrigName.substring(fileOrigName.lastIndexOf("."));
			String prefix = fileOrigName.substring(fileOrigName.lastIndexOf(".") + 1);
			if (!prefix.matches("jpg|png"))
				throw new IllegalArgumentException("图片 JPG/PNG格式.");

			String fullPath = filesPath + "/" + file.getOriginalFilename();
			FileUtil.saveFile(file, fullPath);
		}
		return new ResultResponse<Integer>(0, "OK", files.length);
	}

	@ApiOperation(value = "打包导入照片")
	@PostMapping("/imgs")
	public ResultResponse<String> importImages(@ApiParam(required = false, value = "导入照片压缩包") @Valid MultipartFile file)
			throws IOException, Exception {
		String fileOrigName = file.getOriginalFilename();
		if (!fileOrigName.contains(".")) {
			throw new IllegalArgumentException("Lack of suffix name.");
		}

		fileOrigName = fileOrigName.substring(fileOrigName.lastIndexOf("."));
		String prefix = fileOrigName.substring(fileOrigName.lastIndexOf(".") + 1);

		if (!prefix.equals("zip"))
			throw new IllegalArgumentException("压缩包不是zip格式.");

		String md5 = FileUtil.fileMd5(file.getInputStream());
		String fullPath = filesPath + FileUtil.getPath() + md5 + file.getOriginalFilename();
		FileUtil.saveFile(file, fullPath);
		ZipFile zipFile = new ZipFile(fullPath);
		ZipInputStream zis = new ZipInputStream(file.getInputStream());
		ZipEntry entry = null;
		while ((entry = zis.getNextEntry()) != null) {
			fileOrigName = entry.getName();

			prefix = fileOrigName.substring(fileOrigName.lastIndexOf(".") + 1);
			if (!prefix.matches("jpg|png")) {
				continue;
			}
			File outFile = new File(filesPath + "/" + entry.getName());
			if (!outFile.exists()) {
				outFile.createNewFile();
			}
			BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));

			// create an output stream
			BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outFile));
			byte[] b = new byte[100];
			while (true) {
				int len = bis.read(b);
				if (len == -1)
					break;
				bos.write(b, 0, len);
			}
			// close stream
			bis.close();
			bos.close();
		}
		zis.close();
		return new ResultResponse<String>(0, "OK", file.getOriginalFilename());
	}

	@ApiOperation(value = "获取照片")
	@RequestMapping(value = "/getimg", method = RequestMethod.POST, produces = { MediaType.IMAGE_PNG_VALUE,
			MediaType.IMAGE_JPEG_VALUE })
	public byte[] getImage(@ApiParam(required = true, value = "查询记录编号") @RequestBody @Valid Integer id,
			HttpServletResponse response) throws IOException {

		Candidate c = candidateService.getById(id);
		if (c == null)
			return null;

		File file1 = null, file2 = null;
		boolean isjpg = false;

		file1 = new File(filesPath + "/" + c.getPhone() + ".jpg");
		file2 = new File(filesPath + "/" + c.getPhone() + ".png");

		if (file1 == null & file2 == null)
			return null;
		ByteArrayOutputStream bao = new ByteArrayOutputStream();
		try {
			BufferedImage img = ImageIO.read(file1);
			ImageIO.write(img, "jpg", bao);
			return bao.toByteArray();
		} catch (IOException e) {
			BufferedImage img = ImageIO.read(file2);
			ImageIO.write(img, "png", bao);
			return bao.toByteArray();
		} 
	}
}
